from django.shortcuts import render,HttpResponse

# Create your views here.

import json
from autocmdb import models
from django.views import View

def enterinfo(HARDWARE,networkinfo,diskinfos):
	'''把收集的数据录入到数据库'''
	#基本硬件录入
	for k, v in HARDWARE.items():
		try:
			hardware = models.Hardware.objects.get(minion_id=HARDWARE[k]['id'])
		except:
			hardware = models.Hardware()
		hardware.minion_id = v['id']
		hardware.localhost = v['localhost']
		hardware.manufacturer = v['manufacturer']
		hardware.cpu_model = v['cpu_model']
		hardware.cpuarch = v['cpuarch']
		hardware.kernel = v['kernel']
		hardware.kernelrelease = v['kernelrelease']
		hardware.machine_id = v['machine_id']
		hardware.mem_total = v['mem_total']
		hardware.num_cpus = v['num_cpus']
		hardware.osfullname = v['osfullname']
		hardware.productname = v['productname']
		hardware.serialnumber = v['serialnumber']
		hardware.status = 1
		hardware.save()
	#网卡信息录入
	for k, v in networkinfo.items():
		server = models.Hardware.objects.get(minion_id=k)
		for i, j in v.items():
			for x in j:
				network = models.NetworkInfo.objects.filter(ipaddress=x, server_id=server.id)
				if network:
					pass
				else:
					models.NetworkInfo.objects.create(ipaddress=x, server_id=server.id)
	#挂载磁盘录入
	for k, v in diskinfos.items():
		server = models.Hardware.objects.get(minion_id=k)
		for i, j in v.items():
			diskinfo = models.DiskUseInfo.objects.filter(mount=i, server_id=server.id).first()
			if diskinfo:
				models.DiskUseInfo.objects.filter(id=diskinfo.id).update(mount=str(i), blocks=j['1K-blocks'],
				                                                         capacity=j['capacity'],
				                                                         filesystem=j['filesystem'],
				                                                         server_id=server.id)
			else:
				models.DiskUseInfo.objects.create(mount=str(i), blocks=j['1K-blocks'], capacity=j['capacity'],
				                                  filesystem=j['filesystem'], server_id=server.id)


# def updatehardware(request):
# 	'''资产信息收集'''
# 	if request.method == 'GET':
# 		try:
# 			from autocmdb import getHardware
# 			salt = getHardware.SaltClient()
# 			#服务器基本信息收集
# 			HARDWARE = salt.gethardware('*')
#
# 			#网卡信息收集
# 			networkinfo = salt.getnetworkinfo('*')
#
# 			#磁盘信息收集
# 			diskinfos = salt.getdiskinfo('*')
#
# 			try:
# 				enterinfo(HARDWARE, networkinfo, diskinfos)
# 				return HttpResponse(json.dumps({'code':'1000','message':'收录完成'},ensure_ascii=False))
# 			except:
# 				return HttpResponse(json.dumps({'code':'1000','message':'录入数据库过程异常'},ensure_ascii=False))
# 		except:
# 			return HttpResponse(json.dumps({'code': '1001', 'message': '收集失败，收集脚本在过程中出现异常'}, ensure_ascii=False))


def test(request):
	print(request.META)
	# from script import saltcollect
	# salt = saltcollect.SaltApi()
	# result = {'Name':'Beam'}
	# foo = salt.getresult('*', 'test.foo', None)
	# print(foo)
	# return HttpResponse(json.dumps(foo,ensure_ascii=False))
	return HttpResponse('123')

def cmdbcollect(request):
	if request.method == 'GET':
		serid = request.GET.get('serid',None)
		print(serid)
		from autocmdb import getHardware
		salt = getHardware.SaltClient()
		result = {'status':False,'message':None}
		if serid == '0':
			#服务器基本信息收集
			HARDWARE = salt.gethardware('*')
			#网卡信息收集
			networkinfo = salt.getnetworkinfo('*')
			#磁盘信息收集
			diskinfos = salt.getdiskinfo('*')
			#录入到数据库
			enterinfo(HARDWARE, networkinfo, diskinfos)
			result['status'] = True
			result['message'] = '全部更新成功'
			return HttpResponse(json.dumps(result,ensure_ascii=False))
		if serid:
			#服务器基本信息收集
			HARDWARE = salt.gethardware(serid)
			#网卡信息收集
			networkinfo = salt.getnetworkinfo(serid)
			#磁盘信息收集
			diskinfos = salt.getdiskinfo(serid)
			#录入到数据库
			enterinfo(HARDWARE, networkinfo, diskinfos)
			result['status'] = True
			result['message'] = '%s 更新成功' % serid
			return HttpResponse(json.dumps(result,ensure_ascii=False))
		else:
			result['status'] = False
			result['message'] = '发生未知错误，更新失败。'
			return HttpResponse(json.dumps(result, ensure_ascii=False))

class Cmdbcollect(View):
	def get(self,request,serid,**kwargs):
		print(serid)
		try:
			from autocmdb import getHardware
			salt = getHardware.SaltClient()
			#服务器基本信息收集
			HARDWARE = salt.gethardware('*')
			#网卡信息收集
			networkinfo = salt.getnetworkinfo('*')
			#磁盘信息收集
			diskinfos = salt.getdiskinfo('*')
			try:
				enterinfo(HARDWARE, networkinfo, diskinfos)
				return HttpResponse(json.dumps({'code':'1000','message':'收录完成'},ensure_ascii=False))
			except:
				return HttpResponse(json.dumps({'code':'1000','message':'录入数据库过程异常'},ensure_ascii=False))
		except:
			return HttpResponse(json.dumps({'code': '1001', 'message': '收集失败，收集脚本在过程中出现异常'}, ensure_ascii=False))

	def post(self,request,sid,**kwargs):
		pass
		# print(sid)
		# return HttpResponse(json.dumps({'code': '1000', 'message': '收录完成'}, ensure_ascii=False))


